package vn.vfriends.id.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import vn.vfriends.id.bean.GroupBean;
import vn.vfriends.id.jpa.entity.Group;

/**
 *
 * @author tuan@vfriends.vn
 */
@FacesConverter(value = "groupConverter")
public class GroupConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String name) {
        if (name == null || name.length() == 0) {
            return null;
        }
        GroupBean bean = (GroupBean) facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, "groupBean");
        if (bean == null) {
            return null;
        }
        return bean.getGroup(name);
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
        if (object == null) {
            return null;
        }
        if (object instanceof Group) {
            Group group = (Group) object;
            return group.getName();
        } else {
            throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: vn.vfriends.id.jpa.entity.Group");
        }
    }
}